import { debounce } from "@/utils/core.js";
/**
 鼠标移动到对象显示出来虚线
 */
const initManager = (canvas, minimap, $store) => {
  let ctx = canvas.getSelectionContext(),
    aligningLineWidth = 3,
    aligningLineColor = "rgb(255,255,0)",
    PS = [];

  const createCanvasEl = () => {
    let bg = canvas.getObjects("_lxw_bg")[0];
    //console.log(canvas.viewportTransform);

    //这个尺寸会变化，根据放大缩小
    var designSize = {
      width: bg.width,
      height: bg.height
    };
    var originalVPT = canvas.viewportTransform;

    // zoom to fit the design in the display canvas
    //
    var designRatio = fabric.util.findScaleToFit(designSize, canvas);

    // zoom to fit the display the design in the minimap.
    var minimapRatio = fabric.util.findScaleToFit(canvas, minimap);

    var scaling = minimap.getRetinaScaling();

    // console.log(
    //   "designRatio",
    //   designRatio,
    //   minimapRatio,
    //   scaling,
    //   canvas.getZoom()
    // );

    var finalWidth = designSize.width * designRatio;
    var finalHeight = designSize.height * designRatio;

    canvas.viewportTransform = [
      designRatio,
      0,
      0,
      designRatio,
      //减去原来的偏移
      (canvas.getWidth() - finalWidth) / 2 - bg.left * designRatio,
      (canvas.getHeight() - finalHeight) / 2 - bg.top * designRatio
    ];
    //console.log(minimapRatio, scaling);

    //生成缩放的图片
    var _canvas = canvas.toCanvasElement(minimapRatio * scaling);

    //还原回来数据
    canvas.viewportTransform = originalVPT;

    return _canvas;
  };

  //如果是更新内容
  let updateMiniMap = () => {
    var _canvas = createCanvasEl();
    minimap.backgroundImage._element = _canvas;
    minimap.requestRenderAll();
  };

  //如果是拖动?
  let updateMiniMapVP = () => {
    let bg = canvas.getObjects("_lxw_bg")[0];
    //console.log(canvas.viewportTransform);

    //这个尺寸会变化，根据放大缩小
    var designSize = {
      width: bg.width,
      height: bg.height
    };

    var rect = minimap.getObjects()[0];
    var designRatio = fabric.util.findScaleToFit(designSize, canvas);
    var totalRatio = fabric.util.findScaleToFit(designSize, minimap);

    var finalRatio = designRatio / canvas.getZoom();
    rect.scaleX = finalRatio;
    rect.scaleY = finalRatio;

    console.log(bg.lineCoords.tl.x, bg.lineCoords.tl.y);

    //定位鹰眼拖动框的位置
    rect.left =
      //距离左边的距离
      minimap.backgroundImage.left -
      (canvas.viewportTransform[4] * totalRatio) / canvas.getZoom();

    rect.top =
      //距离上面的距离
      minimap.backgroundImage.top -
      //缩放到最大，然后根据比例继续缩放
      (canvas.viewportTransform[5] * totalRatio) / canvas.getZoom();

    //定位鹰眼拖动框的位置

    minimap.requestRenderAll();
  };

  let initMinimap = () => {
    var _canvas = createCanvasEl();
    var backgroundImage = new fabric.Image(_canvas);
    backgroundImage.scaleX = 1 / canvas.getRetinaScaling();
    backgroundImage.scaleY = 1 / canvas.getRetinaScaling();
    minimap.centerObject(backgroundImage);
    minimap.backgroundColor = "yellow";
    minimap.backgroundImage = backgroundImage;
    minimap.requestRenderAll();

    // console.log(
    //   backgroundImage.width / canvas.getRetinaScaling(),
    //   backgroundImage.height / canvas.getRetinaScaling(),
    //   canvas.getRetinaScaling(),
    //   minimap.width,
    //   minimap.height,
    //   backgroundImage.top,
    //   backgroundImage.left
    // );

    //拖动区域
    var minimapView = new fabric.Rect({
      top: backgroundImage.top,
      left: backgroundImage.left,
      width: backgroundImage.width / canvas.getRetinaScaling(),
      height: backgroundImage.height / canvas.getRetinaScaling(),
      fill: "rgba(0, 255, 100, 0.3)",
      cornerSize: 6,
      transparentCorners: false,
      cornerColor: "blue",
      strokeWidth: 0
    });
    minimapView.controls = {
      br: fabric.Object.prototype.controls.br
    };
    minimap.add(minimapView);
  };

  //注册事件
  let KEYS = [
    {
      isKey(e) {
        return e.code == "KeyC" && e.ctrlKey;
      },
      action: "copy"
    },
    {
      isKey(e) {
        return e.code == "KeyV" && e.ctrlKey;
      },
      action: "paste"
    },
    {
      isKey(e) {
        return e.code == "Delete";
      },
      action: "del"
    },
    {
      isKey(e) {
        return e.code == "KeyG" && e.ctrlKey;
      },
      action: "group"
    },
    {
      isKey(e) {
        return e.code == "KeyU" && e.ctrlKey;
      },
      action: "ungroup"
    },
    {
      isKey(e) {
        return e.code == "KeyA" && e.ctrlKey;
      },
      action: "select"
    },
    {
      isKey(e) {
        return e.code == "KeyZ" && e.ctrlKey;
      },
      action: "undo"
    },
    {
      isKey(e) {
        return e.code == "KeyY" && e.ctrlKey;
      },
      action: "redo"
    }
  ];

  //执行快捷键操作
  document.onkeydown = e => {
    console.log("keyup", e);

    KEYS.map(o => {
      if (o.isKey(e)) {
        //执行命令
        $store.dispatch(o.action);

        event.preventDefault();
        event.stopPropagation();
      }
    });
  };

  //绘制
  let drawLine = points => {
    ctx.save();
    ctx.lineWidth = aligningLineWidth;
    ctx.strokeStyle = aligningLineColor;
    ctx.setLineDash([6, 6]);
    ctx.beginPath();

    ctx.moveTo(points[0].x, points[0].y);

    //把4个点连接起来
    ctx.lineTo(points[1].x, points[1].y);
    ctx.lineTo(points[2].x, points[2].y);
    ctx.lineTo(points[3].x, points[3].y);
    ctx.lineTo(points[0].x, points[0].y);

    ctx.stroke();
    ctx.restore();
  };

  canvas.on("mouse:over", e => {
    if (e.target == null) return;

    //如果是当前选中的对象，就不要再显示
    if (e.target == canvas.getActiveObject()) return;

    //得到四个角的坐标
    let lineCoords = e.target.lineCoords;
    PS = [lineCoords.bl, lineCoords.br, lineCoords.tr, lineCoords.tl];

    canvas.renderAll();
  });

  canvas.on("before:render", () => {
    if (canvas.contextTop) {
      canvas.clearContext(canvas.contextTop);
    }
  });

  //清除线条
  canvas.on("after:render", () => {
    if (PS.length > 0) drawLine(PS);
  });

  //应该所有的事件放到一个里面
  canvas.on("mouse:wheel", e => {
    var delta = e.e.deltaY;
    var zoom = canvas.getZoom();

    let preZoom = zoom;
    //新的缩放比例
    zoom *= 0.999 ** delta;
    if (zoom > 10) zoom = 10;
    if (zoom < 0.1) zoom = 0.1;

    //console.log("canvas", event.pageX, event.pageY);
    //总是从中心点缩放...
    let zoomPoint = new fabric.Point(canvas.width / 2, canvas.height / 2);

    //根据鼠标点进行放大缩小
    //减去偏移量，我操。。。。。
    zoomPoint = new fabric.Point(
      //鼠标在屏幕的位置 - 对象的屏幕偏移量
      e.e.pageX - canvas.wrapperEl.offsetLeft,
      e.e.pageY - canvas.wrapperEl.offsetTop
    );

    let bg = canvas.getObjects("_lxw_bg")[0];

    //bg的位置
    let x = 0;
    let y = 0;

    //鼠标放大缩小比例
    let bl = zoom / preZoom;

    //得到画布目前的偏移位置和大小

    // if (bgRect.width <= canvas.width) {
    //   x = (canvas.width - bgRect.width * bl) / 2;
    // } else {
    //   //已鼠标的点放大缩小
    //   //缩放前，鼠标在左侧
    //   let newLeft = (bgRect.left - zoomPoint.x) * bl + zoomPoint.x;
    //   let newRight =
    //     (bgRect.left + bgRect.width - zoomPoint.x) * bl + zoomPoint.x;

    //   //最多100的距离
    //   if (zoomPoint.x < bgRect.left) {
    //     if (newLeft > 100) x = 100;
    //     else x = newLeft;
    //   } else if (zoomPoint.x > bgRect.left + bgRect.width) {
    //     if (newRight > 100) x = canvas.width - bgRect.width - 100;
    //     else x = newLeft;
    //   } else {
    //     x = newLeft;
    //   }
    // }

    //缩略图的大小跟画布的大小成正比，画布的1.5倍？

    //如果画布小于视窗大小，就居中显示
    //如果鼠标在视窗外面，画布离视窗的边缘不能大于100，大于100也按照100计算
    //如果鼠标在视窗里面，画布按照鼠标点进行放大

    //关键寻找缩放的地方

    canvas.zoomToPoint(zoomPoint, zoom);

    let bgRect = bg.getBoundingRect();
    console.log(bgRect);
    console.log(canvas.viewportTransform[4], canvas.viewportTransform[5]);
    // canvas.setZoom(zoom);
    // console.log(canvas);

    // //重新定义位置，需要重新画布的偏移
    // canvas.viewportTransform[4] = x - bg.left * zoom;
    // canvas.viewportTransform[5] = y - bg.top * zoom;
    canvas.viewportTransform[4] = 100;

    //updateMiniMapVP();

    PS.length = 0;
    canvas.renderAll();

    // console.log(
    //   bg.getBoundingRect(),
    //   canvas.viewportTransform[4],
    //   canvas.viewportTransform[5]
    // );

    e.e.preventDefault();
    e.e.stopPropagation();
  });

  canvas.on("mouse:out", e => {
    if (e.target == null) return;

    PS.length = 0;
    canvas.renderAll();
  });

  canvas.on("mouse:down", e => {
    if (e.target == null) return;

    PS.length = 0;
    canvas.renderAll();
  });

  //var debouncedMiniMap = debounce(updateMiniMap, 250);

  canvas.on("object:modified", function() {
    //updateMiniMap();
  });

  //   initMinimap();
  //   updateMiniMapVP();
};

export default initManager;
